package com.lizx.framework.web.smart.framework.core.helper;

import com.lizx.framework.web.smart.framework.core.annotations.SmartInject;
import com.lizx.framework.web.smart.framework.core.utils.SmartReflectionUtil;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 依赖注入加载类
 *
 * @Author: lizx
 * @Description:
 * @Date: Create in 2019/1/18 9:42 AM
 */
public class SmartIocHelper {
    static {
        //获取所有的bean映射关系
        Map<Class<?>, Object> beanMap = SmartBeanHelper.getBeanMap();
        if (MapUtils.isNotEmpty(beanMap)) {
            for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) {
                Class<?> beanClass = beanEntry.getKey();
                Object beanInstance = beanEntry.getValue();
                //获取bean的成员变量
                Field[] beanFields = beanClass.getDeclaredFields();
                if (ArrayUtils.isNotEmpty(beanFields)) {
                    for (Field beanField : beanFields) {
                        //如果当前beanField带有Inject注解
                        if (beanField.isAnnotationPresent(SmartInject.class)) {
                            //获取beanField的实例
                            Object beanFieldInstance = beanMap.get(beanField.getType());
                            if (beanFieldInstance != null) {
                                //通过反射初始化beanField的值
                                SmartReflectionUtil.setField(beanInstance, beanField, beanFieldInstance);
                            }
                        }
                    }
                }
            }
        }
    }
}
